﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Web.Script.Serialization;

namespace Heyu.Utility
{
    public class JsonUtility
    {
        /// <summary>
        /// DataTable序列化
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static string SerializeDataTable(DataTable dt)
        {
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            List<Dictionary<string, object>> list = new List<Dictionary<string, object>>();
            foreach (DataRow dr in dt.Rows)//每一行信息，新建一个Dictionary<string,object>,将该行的每列信息加入到字典
            {
                Dictionary<string, object> result = new Dictionary<string, object>();
                foreach (DataColumn dc in dt.Columns)
                {
                    result.Add(dc.ColumnName, dr[dc].ToString());
                }
                list.Add(result);
            }
            return serializer.Serialize(list);//调用Serializer方法 
        }


        /// <summary>
        /// DataTable反序列化
        /// </summary>
        /// <param name="strJson"></param>
        /// <returns></returns>
        public static DataTable DeserializerTable(string strJson)
        {
            DataTable dt = new DataTable();
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            // var obj = serializer.DeserializeObject(strJson);//反序列化
            ArrayList arralList = serializer.Deserialize<ArrayList>(strJson);//反序列化ArrayList类型
            if (arralList.Count > 0)//反序列化后ArrayList个数不为0
            {
                foreach (Dictionary<string, object> row in arralList)
                {
                    if (dt.Columns.Count == 0)//新建的DataTable中无任何信息，为其添加列名及类型
                    {
                        foreach (string key in row.Keys)
                        {
                            dt.Columns.Add(key, row[key].GetType());//添加dt的列名
                        }
                    }
                    DataRow dr = dt.NewRow();
                    foreach (string key in row.Keys)//讲arrayList中的值添加到DataTable中
                    {

                        dr[key] = row[key];//添加列值
                    }
                    dt.Rows.Add(dr);//添加一行
                }
            }
            return dt;
        }


        #region DataSet转换成Json格式
        /// <summary>  
        /// DataSet转换成Json格式  
        /// </summary>  
        /// <param name="ds">DataSet</param> 
        /// <returns></returns>  
        public static string DataSetToJson(DataSet ds)
        {
            StringBuilder json = new StringBuilder();

            foreach (DataTable dt in ds.Tables)
            {
                json.Append("{\"");
                json.Append(dt.TableName);
                json.Append("\":");
                json.Append(DataTableToJson(dt));
                json.Append("}");
            }
            return json.ToString();
        }
        #endregion

        /// <summary>
        /// Msdn
        /// </summary>
        /// <param name="jsonName"></param>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static string DataTableToJson(DataTable dt, string jsonName = "")
        {
            StringBuilder Json = new StringBuilder();
            Json.Append("{\"" + (jsonName == "" ? dt.TableName : jsonName) + "\":[");
            if (dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    Json.Append("{");
                    for (int j = 0; j < dt.Columns.Count; j++)
                    {
                        Json.Append("\"" + dt.Columns[j].ColumnName.ToString() + "\":\"" + dt.Rows[i][j].ToString() + "\"");
                        if (j < dt.Columns.Count - 1)
                        {
                            Json.Append(",");
                        }
                    }
                    Json.Append("}");
                    if (i < dt.Rows.Count - 1)
                    {
                        Json.Append(",");
                    }
                }
            }
            Json.Append("]}");
            return Json.ToString();
        }


        /// <summary>
        /// 对象转JSON     
        /// </summary>     
        /// <param name="obj">对象</param>     
        /// <returns>JSON格式的字符串</returns>     
        public static string ScriptSerialize<T>(T t)
        {
            JavaScriptSerializer jss = new JavaScriptSerializer();
            return jss.Serialize(t);
        }

        public static T ScriptDeserialize<T>(string strJson)
        {
            JavaScriptSerializer js = new JavaScriptSerializer();
            return js.Deserialize<T>(strJson);
        }


        /// <summary>
        /// 将Json转换为Dic
        /// </summary>
        /// <param name="Json"></param>
        /// <returns></returns>
        public static Dictionary<string, object> JsonToDic(string Json)
        {
            Dictionary<string, object> dic = new Dictionary<string, object>();
            JavaScriptSerializer jss = new JavaScriptSerializer();
            try
            {
                dic = jss.Deserialize<Dictionary<string, object>>(Json);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            return dic;
        }


        ///// <summary>    
        ///// DataTable转Json    
        ///// </summary>    
        ///// <param name="tb"></param>    
        ///// <returns></returns>    
        //public static string DataTableToJson(DataTable tb)
        //{
        //    JavaScriptSerializer jss = new JavaScriptSerializer();
        //    ArrayList dic = new ArrayList();
        //    foreach (DataRow row in tb.Rows)
        //    {
        //        Dictionary<string, object> drow = new Dictionary<string, object>();
        //        foreach (DataColumn col in tb.Columns)
        //        {
        //            object oVal = row[col.ColumnName];
        //            if (oVal.GetType() == typeof(DateTime) && oVal != DBNull.Value)
        //            {
        //                oVal = Convert.ToDateTime(oVal).ToString("yyyy-MM-dd HH:mm:ss");
        //            }
        //            drow.Add(col.ColumnName, oVal);
        //        }
        //        dic.Add(drow);
        //    }
        //    return jss.Serialize(dic);
        //}

        ///// <summary>    
        ///// Json 转 DataTalbe
        ///// </summary>    
        ///// <param name="tb"></param>    
        ///// <returns></returns>    
        //public static DataTable JsonToDataTable(string json)
        //{
        //    JavaScriptSerializer jss = new JavaScriptSerializer();
        //    ArrayList dic = jss.Deserialize<ArrayList>(json);
        //    DataTable tb = new DataTable();
        //    if (dic.Count > 0)
        //    {
        //        foreach (Dictionary<string, object> drow in dic)
        //        {
        //            if (tb.Columns.Count == 0)
        //            {
        //                foreach (string key in drow.Keys)
        //                {
        //                    tb.Columns.Add(key, drow[key].GetType());
        //                }
        //            } DataRow row = tb.NewRow();
        //            foreach (string key in drow.Keys)
        //            {
        //                row[key] = drow[key];
        //            }
        //            tb.Rows.Add(row);
        //        }
        //    }
        //    return tb;
        //}


        /// <summary>
        /// 将json转换为DataTable
        /// </summary>
        /// <param name="strJson">得到的json</param>
        /// <returns></returns>
        private static DataTable JsonToDataTable(string strJson)
        {
            //转换json格式
            strJson = strJson.Replace(",\"", "*\"").Replace("\":", "\"#").ToString();
            //取出表名   
            var rg = new Regex(@"(?<={)[^:]+(?=:\[)", RegexOptions.IgnoreCase);
            string strName = rg.Match(strJson).Value;
            DataTable tb = null;
            //去除表名   
            strJson = strJson.Substring(strJson.IndexOf("[") + 1);
            strJson = strJson.Substring(0, strJson.IndexOf("]"));

            //获取数据   
            rg = new Regex(@"(?<={)[^}]+(?=})");
            MatchCollection mc = rg.Matches(strJson);
            for (int i = 0; i < mc.Count; i++)
            {
                string strRow = mc[i].Value;
                string[] strRows = strRow.Split('*');

                //创建表   
                if (tb == null)
                {
                    tb = new DataTable();
                    tb.TableName = strName;
                    foreach (string str in strRows)
                    {
                        var dc = new DataColumn();
                        string[] strCell = str.Split('#');

                        if (strCell[0].Substring(0, 1) == "\"")
                        {
                            int a = strCell[0].Length;
                            dc.ColumnName = strCell[0].Substring(1, a - 2);
                        }
                        else
                        {
                            dc.ColumnName = strCell[0];
                        }
                        tb.Columns.Add(dc);
                    }
                    tb.AcceptChanges();
                }

                //增加内容   
                DataRow dr = tb.NewRow();
                for (int r = 0; r < strRows.Length; r++)
                {
                    dr[r] = strRows[r].Split('#')[1].Trim().Replace("，", ",").Replace("：", ":").Replace("\"", "");
                }
                tb.Rows.Add(dr);
                tb.AcceptChanges();
            }

            return tb;
        }


    }
}
